﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Collections;


using Cards.Objects;
using Cards.Util;

namespace Cards.GUI
{
    public partial class INS_VNPockerStage : INS_Stage
    {
        public static int sWinPos = 0;
        public static int sRemainPlayers = 4;
        public static int sSkippedPlayers = 0;
        public static Boolean sWin = false;
        public static int sWinPlayerPos = -1;
        public static long sLoseRate = 1;
        public static int sFirstWinPlayer = -1;
        public static int sPreviousTurnPlayer = -1;

        
        public INS_VNPockerStage(int _x, int _y, int _width, int _height, Form _parent, int _numOfPlayers, bool _networkPlaying = false)
        {

            sSide = 0;
            m_winParent = _parent;
            this.x = _x;
            this.y = _y;
            m_width = _width;
            m_height = _height;

            m_numOfPlayers = _numOfPlayers;
            m_insPackOfCards = new INS_PackOfCards(Constants.s_playerWidth / 2, Constants.s_playerHeight + Constants.s_alphay,
                                     global::Cards.Properties.Resources.bobai2, this,
                                     Constants.s_cardContainerWidth, Constants.s_cardContainerHeight);


            m_stage = new CVNPockerStage(this);

            m_insPlayer = new INS_VNPockerPlayer[m_numOfPlayers];

            int playerIdex = 0;

            if (_networkPlaying == false)
            {
                m_insPlayer[0] = new INS_VNPockerPlayer(Constants.s_posx_player1, Constants.s_posy_player1,
                                                    0, MainFrame.s_loginName, global::Cards.Properties.Resources.nguoichoi1, this, (int)PLAYER_TYPE.HUMAN,
                                                    Constants.s_playerWidth, Constants.s_playerHeight, 0,
                                                    Constants.s_playerHeight - (Constants.s_cardHeight + Constants.s_alphay), Constants.VNPOCKER_NUMOFCARDS,
                                                    Constants.VNPOCKER_NUMOFCARDS);
                playerIdex++;
                m_insPlayer[1] = new INS_VNPockerPlayer(Constants.s_posx_player2, Constants.s_posy_player2,
                                                    1, "Máy 1", global::Cards.Properties.Resources.nguoichoi2, this, PLAYER_TYPE.COMPUTER,
                                                    Constants.s_playerWidth, Constants.s_playerHeight, 0,
                                                    Constants.s_playerHeight - (Constants.s_cardHeight + Constants.s_alphay), Constants.VNPOCKER_NUMOFCARDS,
                                                    Constants.VNPOCKER_NUMOFCARDS);
                playerIdex++;

                if (playerIdex < m_numOfPlayers)
                {
                    m_insPlayer[2] = new INS_VNPockerPlayer(Constants.s_posx_player3, Constants.s_posy_player3
                                                            , 2, "Máy 2", global::Cards.Properties.Resources.nguoichoi3, this, PLAYER_TYPE.COMPUTER,
                                                            Constants.s_playerWidth, Constants.s_playerHeight, 0, 0, Constants.VNPOCKER_NUMOFCARDS,
                                                            Constants.VNPOCKER_NUMOFCARDS);
                    playerIdex++;

                    if (playerIdex < m_numOfPlayers)
                    {
                        m_insPlayer[3] = new INS_VNPockerPlayer(Constants.s_posx_player4, Constants.s_posy_player4,
                                                            3, "Máy 3", global::Cards.Properties.Resources.nguoichoi4, this, PLAYER_TYPE.COMPUTER,
                                                            Constants.s_playerWidth, Constants.s_playerHeight, 0, 0, Constants.VNPOCKER_NUMOFCARDS,
                                                            Constants.VNPOCKER_NUMOFCARDS);
                    }
                }
            }
            else
            {
                FrmCreateMultiGame frm = MainFrame.m_frmMultiGame;
                PLAYER_TYPE type = (PLAYER_TYPE)((ComboBox)frm.ARRCOMBOPLAYERTYPE[playerIdex]).SelectedIndex;

                if (!MainFrame.s_isServer)
                {
                    type = PLAYER_TYPE.HUMAN;
                }

                m_insPlayer[0] = new INS_VNPockerPlayer(Constants.s_posx_player1, Constants.s_posy_player1,
                                                    0, MainFrame.s_loginName, global::Cards.Properties.Resources.nguoichoi1, this, type,
                                                    Constants.s_playerWidth, Constants.s_playerHeight, 0,
                                                    Constants.s_playerHeight - (Constants.s_cardHeight + Constants.s_alphay), Constants.VNPOCKER_NUMOFCARDS,
                                                    Constants.VNPOCKER_NUMOFCARDS);

                playerIdex++;
                if (playerIdex < m_numOfPlayers)
                {
                    int idxComp = 1;
                    String name = "";

                    type = (PLAYER_TYPE)((ComboBox)frm.ARRCOMBOPLAYERTYPE[playerIdex]).SelectedIndex;

                    if (!MainFrame.s_isServer)
                    {
                        type = PLAYER_TYPE.HUMAN;
                    }

                    name = "";
                    if (type == PLAYER_TYPE.HUMAN)
                    {
                        name = ((Label)frm.ARRLABELPLAYERNAME[playerIdex]).Text;
                    }
                    
                    if (name == "")
                    {
                        name = "Máy " + idxComp;
                        idxComp++;
                    }

                    m_insPlayer[1] = new INS_VNPockerPlayer(Constants.s_posx_player2, Constants.s_posy_player2,
                                                        1, name, global::Cards.Properties.Resources.nguoichoi2, this, type,
                                                        Constants.s_playerWidth, Constants.s_playerHeight, 0,
                                                        Constants.s_playerHeight - (Constants.s_cardHeight + Constants.s_alphay), Constants.VNPOCKER_NUMOFCARDS,
                                                        Constants.VNPOCKER_NUMOFCARDS);
                    playerIdex++;

                    if (playerIdex < m_numOfPlayers)
                    {
                        type = (PLAYER_TYPE)((ComboBox)frm.ARRCOMBOPLAYERTYPE[playerIdex]).SelectedIndex;

                        if (!MainFrame.s_isServer)
                        {
                            type = PLAYER_TYPE.HUMAN;
                        }

                        name = "";
                        if (type == PLAYER_TYPE.HUMAN)
                        {
                            name = ((Label)frm.ARRLABELPLAYERNAME[playerIdex]).Text;
                        }

                        if (name == "")
                        {
                            name = "Máy " + idxComp;
                            idxComp++;
                        }


                        m_insPlayer[2] = new INS_VNPockerPlayer(Constants.s_posx_player3, Constants.s_posy_player3
                                                                , 2, name, global::Cards.Properties.Resources.nguoichoi3, this, type,
                                                                Constants.s_playerWidth, Constants.s_playerHeight, 0, 0, Constants.VNPOCKER_NUMOFCARDS,
                                                                Constants.VNPOCKER_NUMOFCARDS);
                        playerIdex++;

                        if (playerIdex < m_numOfPlayers)
                        {
                            type = (PLAYER_TYPE)((ComboBox)frm.ARRCOMBOPLAYERTYPE[playerIdex]).SelectedIndex;

                            if (!MainFrame.s_isServer)
                            {
                                type = PLAYER_TYPE.HUMAN;
                            }

                            name = "";
                            if (type == PLAYER_TYPE.HUMAN)
                            {
                                name = ((Label)frm.ARRLABELPLAYERNAME[playerIdex]).Text;
                            }

                            if (name == "")
                            {
                                name = "Máy " + idxComp;
                                idxComp++;
                            }

                            m_insPlayer[3] = new INS_VNPockerPlayer(Constants.s_posx_player4, Constants.s_posy_player4,
                                                                3, name, global::Cards.Properties.Resources.nguoichoi4, this, type,
                                                                Constants.s_playerWidth, Constants.s_playerHeight, 0, 0, Constants.VNPOCKER_NUMOFCARDS,
                                                                Constants.VNPOCKER_NUMOFCARDS);
                        }
                    }
                }
            }

            Init();
        }

        public override void Init()
        {
            base.Init();

            arrivedPlayers.Clear();
            sFirstWinPlayer = -1;
            sWinPos = 0;
            sRemainPlayers = m_numOfPlayers;
            sSkippedPlayers = 0;
            sWin = false;
            sWinPlayerPos = -1;
            sPlay = false;
            sFirstPlayingPlayer = null;
            sLoseRate = 1;
            sBetMoney = 5000;
            sPreviousTurnPlayer = -1;
            sRemainPlayers = NUMPLAYERS;

            m_numOfCards = Constants.VNPOCKER_NUMOFCARDS;
            m_maxNumOfCards = Constants.VNPOCKER_NUMOFCARDS;
        }

        public override void CreateButton()
        {
            base.CreateButton();

            m_btnPlay = new Button();
            m_btnPlay.Text = "Đánh";
            m_btnPlay.ForeColor = Color.White;
            m_btnPlay.Size = new Size(new Point(80, 22));
            m_btnPlay.Location = new Point(60, Constants.s_playerHeight * 2
                                            + Constants.s_cardContainerHeight + 21);
            m_btnPlay.BackColor = Color.DarkMagenta;
            m_btnPlay.Click += new EventHandler(btnPlay_click);

            m_btnSkip = new Button();
            m_btnSkip.Text = "Bỏ qua";
            m_btnSkip.ForeColor = Color.White;
            m_btnSkip.Size = new Size(new Point(80, 22));
            m_btnSkip.Location = new Point(142, Constants.s_playerHeight * 2
                                            + Constants.s_cardContainerHeight + 21);
            m_btnSkip.BackColor = Color.DarkMagenta;
            m_btnSkip.Click += new EventHandler(btnSkip_click);

            m_btnSortCards = new Button();
            m_btnSortCards.Text = "Sắp xếp";
            m_btnSortCards.ForeColor = Color.White;
            m_btnSortCards.Size = new Size(new Point(80, 22));
            m_btnSortCards.Location = new Point(230, Constants.s_playerHeight * 2
                                            + Constants.s_cardContainerHeight + 21);
            m_btnSortCards.BackColor = Color.DarkMagenta;
            m_btnSortCards.Click += new EventHandler(btnSort_click);

            this.Controls.Add(m_btnPlay);
            this.Controls.Add(m_btnSkip);
            this.Controls.Add(m_btnSortCards);
        }

        protected void btnSort_click(object sender, EventArgs e)
        {
            SortCards();
        }

        public override void InitToContinuePlay()
        {
            base.InitToContinuePlay();

            m_previousCard.Clear();
            m_currentCard.Clear();

            for (int i = 0; i < m_numOfPlayers; i++)
            {
                ((INS_VNPockerPlayer)m_insPlayer[i]).InitCardsPosition();
                ((INS_VNPockerPlayer)m_insPlayer[i]).ResetCardsState();
                ((INS_VNPockerPlayer)m_insPlayer[i]).ResetPlayer();
            }

            arrivedPlayers.Clear();
            if (sFirstWinPlayer == -1)
            {
                sFirstWinPlayer = 0;
            }
            sSide = sFirstWinPlayer;
            sFirstWinPlayer = -1;
            sBeginPlaying = true;
            sWinPos = 0;
            sRemainPlayers = NUMPLAYERS;
            sSkippedPlayers = 0;
            sWin = false;
            sWinPlayerPos = -1;
            sPlay = false;
            sFirstPlayingPlayer = null;
            sLoseRate = 1;
            sBetMoney = 5000;
            sPreviousTurnPlayer = -1;
        }

        public override void AddMoneyForTotalWin(int _posPlayer)
        {
            long tmp = 0;
            for (int i = 0; i < NUMPLAYERS; i++)
            {
                if (i != _posPlayer)
                {
                    m_insPlayer[i].PLAYER.AMOUNT_DECREASE_MONEY += sBetMoney * 2;
                    m_insPlayer[i].PLAYER.AMOUNT_INCREASE_MONEY = 0;
                    m_insPlayer[i].PLAYER.WINMONEY = 0;
                    tmp += sBetMoney * 6;
                }
                else
                {
                    m_insPlayer[i].PLAYER.AMOUNT_INCREASE_MONEY += sBetMoney * 2;
                }
            }
        }

        public override void Step()
        {
            if (!sPlay || m_insPlayer[sSide].PLAYERKIND == PLAYER_TYPE.COMPUTER)
            {
                return;
            }
            ((CVNPockerStage)m_stage).Play();
        }

        public override void Skip()
        {
            if (!sPlay || m_insPlayer[sSide].PLAYERKIND == PLAYER_TYPE.COMPUTER)
            {
                return;
            }

            if (sBeginPlaying)
            {
                return;
            }

            ((CVNPockerStage)m_stage).Skip();
        }

        public override void PlayNextStage()
        {
            if (MainFrame.s_multiType == MULTI_PLAYER_TYPE.SINGLE_PLAYER)
            {
                sPlay = true;

                for (int i = 0; i < NUMPLAYERS; i++)
                {
                    ((INS_VNPockerPlayer)m_insPlayer[i]).DeleteCardsArray();
                    ((INS_VNPockerPlayer)m_insPlayer[i]).Init();
                }

                m_insPackOfCards.RemoveCards();
                m_insPackOfCards.MergeCards();

                m_insPackOfCards.DistributeVNPockerCards();
                //SortCards();

                CreateGUIToReplay();

                m_insPackOfCards.ShowPicture();

                CardsDistributionEffect();

                //m_insPackOfCards.HidePicture();
            }
            else
            {
                PlayNetworkingNextStage();
            }
        }

        public override void BeginToPlay()
        {
            base.BeginToPlay();

            m_insPackOfCards.DistributeVNPockerCards();
            //SortCards();
            CreateGUI();

            CardsDistributionEffect();

            //m_insPackOfCards.HidePicture();
        }

        public override void BeginNetworkPlaying()
        {
            base.BeginNetworkPlaying();

            if (MainFrame.s_isServer)
            {
                // Broadcast begin command
                String msg = IPC.PC.ToCommandMessageString();
                MainFrame.m_frmMultiGame.MULTIGAME.BeginGame(msg);
            }
            else
            {
                m_insPackOfCards.PC.CARDSARRAY = MainFrame.m_frmMultiGame.m_pcArrayCards;
                m_insPackOfCards.PC.INDEX = MainFrame.m_frmMultiGame.m_pcIndex;
            }

            m_insPackOfCards.DistributeVNPockerCards();
            //SortCards();
            CreateGUI();

            CardsDistributionEffect();
        }

        public override void PlayNetworkingNextStage()
        {
            sPlay = true;

            for (int i = 0; i < NUMPLAYERS; i++)
            {
                ((INS_VNPockerPlayer)m_insPlayer[i]).DeleteCardsArray();
                ((INS_VNPockerPlayer)m_insPlayer[i]).Init();
            }

            m_insPackOfCards.RemoveCards();
            m_insPackOfCards.MergeCards();

            if (MainFrame.s_isServer)
            {
                // Broadcast Continue command
                String msg = IPC.PC.ToCommandMessageString();
                MainFrame.m_frmMultiGame.MULTIGAME.ContinueGame(msg);
            }
            else
            {
                m_insPackOfCards.PC.CARDSARRAY = MainFrame.m_frmMultiGame.m_pcArrayCards;
                m_insPackOfCards.PC.INDEX = MainFrame.m_frmMultiGame.m_pcIndex;
            }

            m_insPackOfCards.DistributeVNPockerCards();
            //SortCards();

            CreateGUIToReplay();

            m_insPackOfCards.ShowPicture();

            CardsDistributionEffect();

            //m_insPackOfCards.HidePicture();
        }

        public override void CreateGUIToReplay()
        {
            for (int i = 0; i < m_numOfPlayers; i++)
            {
                ((INS_VNPockerPlayer)m_insPlayer[i]).CreateGUIToReplay();
            }
        }

        public override void CreatePlayerGUI()
        {
            for (int i = 0; i < m_numOfPlayers; i++)
            {
                ((INS_VNPockerPlayer)m_insPlayer[i]).CreateGUI();
                this.Controls.Add(m_insPlayer[i]);
            }
        }

        protected override void timer1_Tick(object sender, EventArgs e)
        {
            timerStartStage.Enabled = false;
            timerStartStage.Stop();
            for (int i = 0; i < NUMPLAYERS; i++)
            {
                ((CVNPockerPlayer)m_insPlayer[i].PLAYER).CreateCardArrays();

                if (((CVNPockerPlayer)m_insPlayer[i].PLAYER).CheckWin4Pigs())
                {
                    MessageBox.Show("Người chơi " + (i + 1) + " đã thắng trắng 4 Heo");
                    AddMoneyForTotalWin(i);
                    EndStage();
                    return;
                }
                else if (((CVNPockerPlayer)m_insPlayer[i].PLAYER).CheckWin6Couple())
                {
                    MessageBox.Show("Người chơi " + (i + 1) + " đã thắng trắng 6 Đôi");
                    AddMoneyForTotalWin(i);
                    EndStage();
                    return;
                }
                else if (((CVNPockerPlayer)m_insPlayer[i].PLAYER).CheckWinSortedArray())
                {
                    MessageBox.Show("Người chơi " + (i + 1) + " đã thắng trắng lốc từ 3 đến A");
                    AddMoneyForTotalWin(i);
                    EndStage();
                    return;
                }
                //else if (m_insPlayer[i].PLAYER.CheckWin5Fines())
                //{
                //    MessageBox.Show("Người chơi " + (i + 1) + " đã thắng trắng 5 Đôi thông");
                //    AddMoneyForTotalWin(i);
                //    EndStage();
                //    return;
                //}
            }

            m_insPlayer[sSide].ReceiveTurn();

            if (MainFrame.s_multiType != MULTI_PLAYER_TYPE.SINGLE_PLAYER)
            {
                if ((m_insPlayer[sSide].PLAYERKIND == (int)PLAYER_TYPE.HUMAN) &&
                    (m_insPlayer[sSide].STT != MainFrame.m_frmMultiGame.GAMEPLAYERID - 1))
                {
                    enableButtonPlay(false);
                    enableButtonSkip(false);
                }
            }
        }
        
        public override void EndStage()
        {
            base.EndStage();

            for (int i = 0; i < m_numOfPlayers; i++)
            {
                if ((!m_insPlayer[i].PLAYER.WIN))
                {
                    if (((MainFrame.s_multiType == MULTI_PLAYER_TYPE.SINGLE_PLAYER) && (m_insPlayer[i].PLAYERKIND == PLAYER_TYPE.COMPUTER))
                        || ((MainFrame.s_multiType != MULTI_PLAYER_TYPE.SINGLE_PLAYER) &&
                            ((m_insPlayer[i].STT != MainFrame.m_frmMultiGame.GAMEPLAYERID - 1))))
                    {
                        m_insPlayer[i].DisplayCards();
                    }
                }
                m_insPlayer[i].AddMoney();
            }
        }

        public override void LockGUI()
        {
            base.LockGUI();
            m_btnSortCards.Enabled = false;
        }

        public override void UnLockGUI()
        {
            base.UnLockGUI();
            m_btnSortCards.Enabled = true;
        }

        public override void EndDistributeCardsEffect()
        {
            if (MainFrame.sFirstPlayInStage)
            {
                INS_Stage.sSide = FindFirstPlayingPlayer();
            }

            base.EndDistributeCardsEffect();

            IPC.HidePicture();
        }
        
        public int FindFirstPlayingPlayer()
        {
            int idx = -1;

            for (int i = 0; i < NUMPLAYERS; i++)
            {
                for (int j = 0; j < this[i].NUMOFCARDS; j++)
                {
                    if (this[i].IC[j].CARD.CARDTYPE == Constants.BABICH)
                    {
                        return i;
                    }
                }
            }

            if (idx == -1)
            {
                int min = 53;
                int val;
                for (int i = 0; i < NUMPLAYERS; i++)
                {
                    val = ArrayUtil.FindMinCard(this[i]);
                    if (val < min)
                    {
                        min = val;
                        idx = i;
                    }
                }
            }

            return idx;
        }
    }
}
